package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.EliteThread
import cn.com.elite.Util
import cn.com.kh.HttpClientProxy
import cn.com.kh.KHDBConfig
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate


/**
 *
 * @Title: main.java.cn.com.callback-autoSendMessageThread
 * @Description:ngsapitask-pa 多线程处理短信
 * @Author: TaoHao
 * @Date 2025/7/11 16:00
 *
 */
class autoSendMessageThread implements  EliteThreadInvoke{

    private static final Logger log = LoggerFactory.getLogger(autoSendMessageThread.class);
    @Override
    public  int doCallBack(EliteBean eliteBean, String content) {
        int runResult = 1;
        log.debug("【autoSendMessageThread】准备处理的线程:" + content);
        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            // 标记线程执行中避免执行时间较长其他线程也开始调用
            String logSQL = '''Update Elitethread
                                   Set Status = 1,
                                    Expand = Date_Format(Now(), '%Y-%m-%d')
                                 Where Type = 'auto_SMS_Thread'
                                   And Content = ? ''';
            int logRes = jt.update(logSQL,content);
            log.debug("【autoSendMessageThread】标记线程执行中-记录执行DB结果：" + logRes);

            String chaxsql='''Select Documentout_Guid, Doctype, Documentto, Documentpath, Documentpath2, Lockedby, Openid, Template_Id, Stringfield1, Msgid
              From Documentout
             Where Doctype In (3, 4, 5)
               And Status = 0
               And Documentout_Guid=?
               And Trialcount < Trialcountlimit''';
            //查找待发送任务
            List getSmsSelectSQL =jt.queryForList(chaxsql,content);

            for (int i = 0; i < getSmsSelectSQL.size(); i++) {
                Map selectResultcm = getSmsSelectSQL.get(i);
                String Documentout_Guid = selectResultcm.get("Documentout_Guid");
                String Doctype = selectResultcm.get("Doctype");
                String Documentto = selectResultcm.get("Documentto");
                String Documentpath = selectResultcm.get("Documentpath");
                String Documentpath2 = selectResultcm.get("Documentpath2");
                String Template_Id = selectResultcm.get("Template_Id");
                String Open_Id = selectResultcm.get("OpenId");
                String URL = selectResultcm.get("Stringfield1");
                String opsource = selectResultcm.get("Lockedby");
                String Msgid = selectResultcm.get("Msgid");

            if (Doctype == "3") {
                doSendSMS(eliteBean, Documentout_Guid, Documentto, Documentpath2, Msgid, Template_Id);

            } else if (Doctype == "4") {
                doSendWXGZH(eliteBean, Documentout_Guid, Documentto, Template_Id, URL, Documentpath2, opsource);

            } else if (Doctype == "5") {
                doSendWXMiniP(eliteBean, Documentout_Guid, Documentto, Template_Id, URL, Documentpath2, opsource);

            } else {
                log.warn("未知的消息类型-本条任务结束");
            }

        }

        }catch (Exception e) {
            log.error("【autoSendMessageThread】准备处理的数据异常!", e);
            runResult = 0;
        }
        return runResult;
    }

    /**
     * 发送短信消息
     * @param s1
     * @param s2
     * @param s3
     */
    public static void doSendSMS(EliteBean eliteBean, String Documentout_Guid, String Documentto, String Documentpath2, String Msgid, String Template_Id) {
        /**
         * @Title:
         * @Description:
         * @Param: 查询该手机号是否黑名单
         * @return: boolean
         * @Author: CC
         * @Date: 2024/6/14
         */
        boolean SendFlag = true; //默认发送短信
        String Check_msg = "";//短信频次校验信息

        log.debug("【START  Doctype=3 】" + Documentto);

        List sblackList = eliteBean.chaxun_sql("select PHONENO   from SPECIALPHONE where PHONENO='" + Documentto + "' and STATUS='1' ", "dataSource");
        if (sblackList.size() > 0) {
            log.debug("【STOP   黑名单手机不允许发送短信,查询到该手机号是黑名单：】" + Documentto);
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Faildescription = '【集中作业平台查询到该手机号是黑名单】', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
            eliteBean.update("delete from  Elitethread Where Content = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 获取短信限制配置信息
            List checkList = eliteBean.chaxun_sql("select dn.documentnu_guid,dn.restriction_name,\n" +
                    "dn.dailyopen,   \n" +
                    "dn.dailylimit,\n" +
                    "DATE_SUB(CURDATE(), INTERVAL + dn.dailylimit-1 DAY) AS dailyday,\n" +
                    "dn.dailytimes,\n" +
                    "dn.weeklyopen,   \n" +
                    "dn.weeklylimit,\n" +
                    "DATE_SUB(CURDATE(), INTERVAL (WEEKDAY(CURDATE()) )  + (dn.weeklylimit-1)*7 DAY) AS weeklyday,\n" +
                    "dn.weeklytimes,\n" +
                    "dn.monthlyopen,  \n" +
                    "dn.monthlylimit,\n" +
                    "DATE_SUB(DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE()) - 1 DAY), INTERVAL dn.monthlylimit-1 MONTH) AS monthday,\n" +
                    "dn.monthlytimes, \n" +
                    "dv.v_doctemplate_id \n" +
                    "from documentnu dn  \n" +
                    "inner join (select documentnu_guid,group_concat('''',doctemplate_id,'''') as 'v_doctemplate_id' from documentnu_rel dr  where dr.doctemplate_id='"+Template_Id+"' group by 		documentnu_guid		) dv on dn.documentnu_guid=dv.documentnu_guid \n" +
                    "where 1=1 and dn.invalid_state=1 ", "dataSource");

            if (checkList.size() > 0) {
                for (int i = 0; i < checkList.size(); i++) {
                    String documentnu_guid = checkList[i].get("documentnu_guid");
                    String SmsName = checkList[i].get("restriction_name");
                    int DailyOpen = checkList[i].get("dailyopen");
                    int DailyLimit = checkList[i].get("dailylimit");
                    String DailyDay = checkList[i].get("dailyday");
                    int DailyTimes = checkList[i].get("dailytimes");
                    int WeekOpen = checkList[i].get("weeklyopen");
                    int WeekLimit = checkList[i].get("weeklylimit");
                    String WeekDay = checkList[i].get("weeklyday");
                    int WeekTimes = checkList[i].get("weeklytimes");
                    int MonthOpen = checkList[i].get("monthlyopen");
                    int MonthLimit = checkList[i].get("monthlylimit");
                    String MonthDay = checkList[i].get("monthday");
                    int MonthTimes = checkList[i].get("monthlytimes");

                    String V_DOCTEMPLATE_ID = checkList[i].get("v_doctemplate_id");

                    //根据时间入参查询documentout表实际发送短信数量
                    List checkcon = eliteBean.chaxun_sql("select " +
                            "       ifnull(sum(case when d.CREATEDDATE>'" + DailyDay + "' then 1 else 0 end),0) AS con_day,\n" +
                            "       ifnull(sum(case when d.CREATEDDATE>'" + WeekDay + "' then 1 else 0 end),0) AS con_week,\n" +
                            "       ifnull(sum(case when d.CREATEDDATE>'" + MonthDay + "' then 1 else 0 end),0) AS con_month\n" +
                            "FROM documentout d \n" +
                            "where d.doctype=3 and d.Status = '1' \n" +
                            "and d.DOCUMENTTO='" + Documentto + "'  \n" +
                            "and d.TEMPLATE_ID in (  SELECT doctemplate_id  FROM  documentnu_rel WHERE documentnu_guid='"+documentnu_guid+"' ) ", "dataSource");

                    int Con_Day = checkcon[0].get("con_day");
                    int Con_Week = checkcon[0].get("con_week");
                    int Con_Month = checkcon[0].get("con_month");

                    log.debug("日限制：" + DailyOpen + "》" + DailyTimes + "》" + Con_Day);
                    log.debug("周限制：" + WeekOpen + "》" + WeekTimes + "》" + Con_Week);
                    log.debug("月限制：" + MonthOpen + "》" + MonthTimes + "》" + Con_Month);
                    //日限制判断
                    if (DailyOpen == 1 && DailyTimes <= Con_Day) {
                        Check_msg = "因命中规则：" + SmsName + "，每【" + DailyLimit + "】日发送限制【" + DailyTimes + "】条规则，无法提交发送。";
                        SendFlag = false;
                        break;
                    } else if (WeekOpen == 1 && WeekTimes <= Con_Week) {
                        Check_msg = "因命中规则：" + SmsName + "，每【" + WeekLimit + "】周发送限制【" + WeekTimes + "】条规则，无法提交发送。";
                        SendFlag = false;
                        break;
                    } else if (MonthOpen == 1 && MonthTimes <= Con_Month) {
                        Check_msg = "因命中规则：" + SmsName + "，每【" + MonthLimit + "】月发送限制【" + MonthTimes + "】条规则，无法提交发送。";
                        SendFlag = false;
                        break;
                    }

                }
            }

            // 校验通过才发短信哦
            if (SendFlag == false) {
                log.debug(Documentto + " STOP：" + Check_msg);
                eliteBean.update("Update Documentout Set Status = '10', Lasttrydatetime = Now(), Finishdatetime = Now() ,check_msg='" + Check_msg + "' Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
                eliteBean.update("delete from  Elitethread Where Content = '" + Documentout_Guid + "'", "dataSource");
            } else if (SendFlag == true) {
                log.debug(Documentto + "：校验通过 开始调用发送API");
                // 开始准备发送
                JSONObject sendResultJson = sendPASms(eliteBean, Documentout_Guid, Documentto, Documentpath2, Msgid, Template_Id);

                if (sendResultJson.getString("code") == "0") {
                    // 发送成功
                    String failCode = GetJV(sendResultJson,"ResultID");
                    String failDesc = GetJV(sendResultJson,"Description")
                    eliteBean.update("Update Documentout Set Status = '1', Failcode = '" + failCode + "', Faildescription = '" + failDesc + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
                    eliteBean.update("delete from  Elitethread Where Content = '" + Documentout_Guid + "'", "dataSource");
                } else {
                    // 发送失败
                    String failCode = GetJV(sendResultJson,"ResultID");
                    String failDesc = GetJV(sendResultJson,"Description");
                    eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + failCode + "', Faildescription = '" + failDesc + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
                    eliteBean.update("delete from  Elitethread Where Content = '" + Documentout_Guid + "'", "dataSource");
                }
            }
        }
    }

    /**
     * 发送公众号消息
     */
    public static void doSendWXGZH(EliteBean eliteBean, String Documentout_Guid, String Open_Id, String Template_Id, String url, String Template_Data, String opsource) {
        int code = 0;
        String msgid = "";
        String msg = "";
        try {
            String apiWXSendTemplateURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWXSendTemplate?opsource=" + opsource;
            JSONObject postBody = new JSONObject();
            JSONObject postData = JSONObject.parseObject(Template_Data);
            postBody.put("touser", Open_Id);
            postBody.put("template_id", Template_Id);
            postBody.put("topcolor", "#FF0000");
            postBody.put("url", url);
            postBody.put("data", postData);
            log.debug("待发送公众号模板消息URL：" + apiWXSendTemplateURL + " 发送内容:" + postBody.toString());

            // 调用发送公众号模板接口
            String sendResult = HttpClientProxy.sendPost(apiWXSendTemplateURL, postBody.toString(), "", 5000);
            JSONObject sendResultJson = JSONObject.parseObject(sendResult);

            // 解析发送返回结果
            code = sendResultJson.getInteger("code");
            msg = sendResultJson.getString("msg");
            msgid = sendResultJson.getJSONObject("data").getString("msgid");
        } catch (Exception e1) {
            log.error("发送公众号模板处理异常", e1);
            code = -1;
        }

        if (code == 1) {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now(), Msgid = '" + msgid + "' Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + code + "', Faildescription = '" + msg + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }
        log.debug("发送公众号模板处理完成...");
    }

    /**
     * 发送小程序消息
     */
    public static void doSendWXMiniP(EliteBean eliteBean, String Documentout_Guid, String Open_Id, String Template_Id, String url, String Template_Data, String opsource) {
        int code = 0;
        String msgid = "";
        String msg = "";
        try {
            String apiWXSendTemplateURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWXSendTemplate?opsource=" + opsource;
            JSONObject postBody = new JSONObject();
            JSONObject postData = JSONObject.parseObject(Template_Data);
            postBody.put("touser", Open_Id);
            postBody.put("template_id", Template_Id);
            postBody.put("miniprogram_state", "trial");
            postBody.put("lang", "zh_CN");
            postBody.put("page", url);
            postBody.put("data", postData);
            log.debug("待发送小程序消息URL：" + apiWXSendTemplateURL + " 发送内容:" + postBody.toString());

            // 调用发送公众号模板接口
            String sendResult = HttpClientProxy.sendPost(apiWXSendTemplateURL, postBody.toString(), "", 5000);
            JSONObject sendResultJson = JSONObject.parseObject(sendResult);

            // 解析发送返回结果
            code = sendResultJson.getInteger("code");
            msg = sendResultJson.getString("msg");
            msgid = sendResultJson.getJSONObject("data").getString("msgid");
        } catch (Exception e1) {
            log.error("发送小程序模板处理异常", e1);
            code = -1;
        }

        if (code == 1) {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now(), Msgid = '" + msgid + "' Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + code + "', Faildescription = '" + msg + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }
        log.debug("发送小程序模板处理完成...");

    }

    public static JSONObject sendPASms(EliteBean eliteBean, String Documentout_Guid, String Documentto, String Documentpath2, String Msgid, String Template_Id) {
        JSONObject resultSendSms = new JSONObject();

        log.debug("sendAliSms参数-Documentout_Guid:" + Documentout_Guid + " Documentto:" + Documentto + " Documentpath2:" + Documentpath2 + " Msgid:" + Msgid + " Template_Id:" + Template_Id);

        try {
            // 获取发送所需要的Token
            String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "EliteInner-API");
            JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(DOMAIN + "/apiGetToken?appid=SMS", "UTF-8", 5000, 0));
            String access_token = apiTokenJson.getJSONObject("data").getString("access_token");

            // 处理发送URL
            String sendURL = KHDBConfig.getAPIURL(eliteBean, "PA-SMS-sendUrl") + "?access_token=" + access_token + "&request_id=" + String.valueOf(System.currentTimeMillis());
            log.debug("调用PA短信发送URL：" + sendURL);

            // 处理头文件
            Map<String, String> headerMap = new HashMap<String, String>();
            headerMap.put("Accept", "application/json");
            headerMap.put("Content-Type", "application/json");

            // Body
            String smsJSON = '''{"messages":[
                                    {
                                        "SendUser":"V_GROUP_PSCP3_FTS_COP_001",
                                        "SendSeriesID":"PA020_S000030945"
                                    }
                                ],
                                "senderID":"V_GROUP_PSCP3_FTS_COP_001"}'''
            JSONObject postBody = JSONObject.fromObject(smsJSON);

            // 1-初始化配置
            postBody.put("senderID", KHDBConfig.getParam(eliteBean, "SMS-SI"));
            postBody.getJSONArray("messages").getJSONObject(0).put("SendUser", KHDBConfig.getParam(eliteBean, "SMS-SU"));
            postBody.getJSONArray("messages").getJSONObject(0).put("SendSeriesID", KHDBConfig.getParam(eliteBean, "SMS-SS"));
            // 2-当前短信信息
            postBody.getJSONArray("messages").getJSONObject(0).put("RequestID", Msgid);
            postBody.getJSONArray("messages").getJSONObject(0).put("TemplateID", Template_Id);
            postBody.getJSONArray("messages").getJSONObject(0).put("MobileNo", Documentto);
            // 3-动态参数添加
            JSONObject smsexp = JSONObject.fromObject(Documentpath2);
            Iterator iter = smsexp.entrySet().iterator();

            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                postBody.getJSONArray("messages").getJSONObject(0).put(entry.getKey().toString(), entry.getValue().toString());
            }
            log.debug("调用PA短信发送Body：" + postBody.toString());

            String postResult = Util.doHttpPostUseHead(sendURL, postBody.toString(), "UTF-8", 120000, 0, headerMap);
            log.debug("调用PA短信发送返回：" + postResult);

            JSONObject resultJson = JSONObject.fromObject(postResult);


            resultSendSms.put("msg", resultJson.getString("msg"));

            if (resultJson.getString("ret") == "0") {
                JSONArray SuccessList = resultJson.getJSONObject("data").getJSONObject("result").getJSONArray("SuccessList");

                for (int i = 0; i < SuccessList.size(); i++) {
                    if (SuccessList.getJSONObject(i).getString("RequestID") == Msgid) {
                        resultSendSms.put("ResultID", GetJV(SuccessList.getJSONObject(i),"ResultID"));
                        resultSendSms.put("code", GetJV(SuccessList.getJSONObject(i),"ResultID"));
                        resultSendSms.put("Description", GetJV(SuccessList.getJSONObject(i),"Description"));
                        log.debug("调用PA短信发送SuccessList结果：" + resultSendSms.toString());

                    }
                }

                if (!resultSendSms.containsKey("ResultID")) {
                    log.debug("检查调用PA短信发送ErrorList结果!");
                    JSONArray ErrorList = resultJson.getJSONObject("data").getJSONObject("result").getJSONArray("ErrorList");
                    for (int j = 0; j < ErrorList.size(); j++) {
                        if (ErrorList.getJSONObject(j).getString("RequestID") == Msgid) {
                            resultSendSms.put("ResultID", GetJV(ErrorList.getJSONObject(j), "ResultID"));
                            resultSendSms.put("code", GetJV(ErrorList.getJSONObject(j),"ResultID"));
                            resultSendSms.put("Description",GetJV( ErrorList.getJSONObject(j),"Description"));
                            log.debug("调用PA短信发送ErrorList结果：" + resultSendSms.toString());

                        }
                    }
                }
            }

            log.debug("调用PA短信发送结果：" + resultSendSms.toString());

        } catch (Exception e1) {
            log.error("调用PA短信发送异常：", e1);
            resultSendSms.put("code", "-1");
            resultSendSms.put("msg", "参数或者程序解析处理异常!");

        }

        return resultSendSms;
    }


    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getLong(getKey));
            } catch (Exception e11) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e1) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                    } catch (Exception e2) {
                        try {
                            Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                        } catch (Exception e3) {
                            Rev_Value = "";
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
                log.debug("GetJV:" + Rev_Value);
            }
        }
        return Rev_Value;
    }
}
